package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.dtflys.forest.annotation.Get;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.IotConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.domain.cache.DeviceCache;
import com.ruoyi.system.service.ISysDeviceService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysBuilding;
import com.ruoyi.system.service.ISysBuildingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 户Controller
 * 
 * @author ruoyi
 * @date 2024-08-07
 */
@RestController
@RequestMapping("/system/building")
public class SysBuildingController extends BaseController
{
    @Autowired
    private ISysBuildingService sysBuildingService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDeviceService sysDeviceService;
    /**
     * 查询户列表
     */
    @PreAuthorize("@ss.hasPermi('system:building:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBuilding sysBuilding)
    {
        startPage();
        sysBuilding.setDeptId(getDeptId());
        List<SysBuilding> list = sysBuildingService.selectSysBuildingList(sysBuilding);
        list.forEach(item ->{
            DeviceCache deviceCache = redisCache.getCacheObject(CacheConstants.IOT_DEVICE + item.getDeviceCode());
            if (deviceCache == null || deviceCache.getHeatQuantity() == null){
                item.setHeatQuantity(0.0);
            }else {
                item.setHeatQuantity(deviceCache.getHeatQuantity());
            }
        });
        return getDataTable(list);
    }

    /**
     * 查询所有楼列表
     */
    @PreAuthorize("@ss.hasPermi('system:building:list')")
    @GetMapping("/allBuild")
    public AjaxResult allBuild(SysBuilding sysBuilding)
    {
        sysBuilding.setDeptId(getDeptId());
        List<SysBuilding> list = sysBuildingService.selectAllSysBuildingList(sysBuilding);
        return success(list);
    }

    /**
     * 查询户绑定设备列表
     * @param buildingId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:building:list')")
    @GetMapping("/iot/{buildingId}/list")
    public AjaxResult iotList(@PathVariable("buildingId") Long buildingId){
        return success(sysDeviceService.selectSysDeviceList(SysDevice.builder().buildingId(buildingId).build()));
    }
    /**
     * 导出户列表
     */
    @PreAuthorize("@ss.hasPermi('system:building:export')")
    @Log(title = "户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBuilding sysBuilding)
    {
        List<SysBuilding> list = sysBuildingService.selectSysBuildingList(sysBuilding);
        ExcelUtil<SysBuilding> util = new ExcelUtil<SysBuilding>(SysBuilding.class);
        util.exportExcel(response, list, "户数据");
    }

    /**
     * 获取户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:building:query')")
    @GetMapping(value = "/{buildingId}")
    public AjaxResult getInfo(@PathVariable("buildingId") Long buildingId)
    {
        return success(sysBuildingService.selectSysBuildingByBuildingId(buildingId));
    }

    /**
     * 新增户
     */
    @PreAuthorize("@ss.hasPermi('system:building:add')")
    @Log(title = "户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBuilding sysBuilding)
    {
        sysBuilding.setDeptId(getDeptId());
        return toAjax(sysBuildingService.insertSysBuilding(sysBuilding));
    }

    /**
     * 批量新增户
     */
    @PreAuthorize("@ss.hasPermi('system:building:add')")
    @Log(title = "批量添加户", businessType = BusinessType.INSERT)
    @PostMapping("/batch/{floor}")
    public AjaxResult batchAdd(@PathVariable Integer floor, @RequestBody List<SysBuilding> sysBuildingList)
    {

        if (sysBuildingList.isEmpty()){
            return error("请选择要添加的户");
        }
        Set<String > totalBathchSet = redisCache.getCacheSet(CacheConstants.BATCH_BUILDING + "*");
        if (totalBathchSet.size() > 5){
            return error("最多添加5个批次");
        }
        Set<String> bathchSet = redisCache.getCacheSet(CacheConstants.BATCH_BUILDING + sysBuildingList.get(0).getBatchKey(getDeptId()));
        if (bathchSet.contains(sysBuildingList.get(0).getBuildingNo())){
            return error("该批次已存在户号：" + sysBuildingList.get(0).getBuildingNo());
        }
        bathchSet.add(sysBuildingList.get(0).getBuildingNo());
        redisCache.setCacheSet(CacheConstants.BATCH_BUILDING + sysBuildingList.get(0).getBatchKey(getDeptId()), bathchSet);
        sysBuildingService.bathInsertSysBuilding(sysBuildingList, floor, getDeptId());
        return success();
    }



    /**
     * 查询批次列表
     */
    @PreAuthorize("@ss.hasPermi('system:building:list')")
    @PostMapping("/batch/list")
    public AjaxResult batchList(@RequestBody SysBuilding sysBuilding)
    {
        Set<String> bathchSet = redisCache.getCacheSet(CacheConstants.BATCH_BUILDING + sysBuilding.getBatchKey(getDeptId()));
        return success(bathchSet);
    }



    /**
     * 修改户
     */
    @PreAuthorize("@ss.hasPermi('system:building:edit')")
    @Log(title = "户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBuilding sysBuilding)
    {
        return toAjax(sysBuildingService.updateSysBuilding(sysBuilding));
    }

    /**
     * 删除户
     */
    @PreAuthorize("@ss.hasPermi('system:building:remove')")
    @Log(title = "户", businessType = BusinessType.DELETE)
    @DeleteMapping("/build/{buildingNo}")
    public AjaxResult remove(@PathVariable String buildingNo)
    {
        return toAjax(sysBuildingService.deleteSysBuildingByBuildingNo(buildingNo));
    }
    /**
     * 删除户
     */
    @PreAuthorize("@ss.hasPermi('system:building:remove')")
    @Log(title = "户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{buildingIds}")
    public AjaxResult remove(@PathVariable Long[] buildingIds)
    {
        return toAjax(sysBuildingService.deleteSysBuildingByBuildingIds(buildingIds));
    }
}
